<template>
  <UserLayout :active-index="activeIndex" :active-menu="activeMenu">
    <div class="house-detail-content">
      <!-- 返回按钮和标题 -->
      <div class="header-section">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <h2 class="page-title">房源详情</h2>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container" v-loading="loading" element-loading-text="正在加载房源详情...">
        <div style="height: 400px; background: rgba(255, 255, 255, 0.9); border-radius: 15px;"></div>
      </div>

      <div v-if="!loading" class="detail-content">
        <!-- 房源图片展示区域 -->
        <div class="image-section">
          <div class="main-image">
            <img :src="houseDetail.images[activeImageIndex]" :alt="houseDetail.title">
          </div>
          <div class="thumbnail-images" v-if="houseDetail.images.length > 1">
            <div
                class="thumbnail"
                v-for="(image, index) in houseDetail.images"
                :key="index"
                :class="{ active: index === activeImageIndex }"
                @click="activeImageIndex = index"
            >
              <img :src="image" :alt="`图片${index + 1}`">
            </div>
          </div>
        </div>

        <!-- 房源信息展示区域 -->
        <div class="info-section">
          <div class="house-header">
            <h1 class="house-title">{{ houseDetail.title }}</h1>
            <div class="house-price">¥{{ houseDetail.price }}<span>/月</span></div>
          </div>

          <div class="house-meta">
            <div class="meta-item">
              <el-icon><House /></el-icon>
              <span>{{ houseDetail.area }}㎡</span>
            </div>
            <div class="meta-item">
              <el-icon><Location /></el-icon>
              <span>{{ houseDetail.address }}</span>
            </div>
            <div class="meta-item">
              <el-icon><OfficeBuilding /></el-icon>
              <span>{{ houseDetail.floorText || `第${houseDetail.floor}层` }}</span>
            </div>
            <div class="meta-item">
              <el-icon><Sunny /></el-icon>
              <span>{{ houseDetail.orientation }}</span>
            </div>
          </div>

          <div class="house-features">
            <div class="feature-item">
              <span class="label">户型:</span>
              <span class="value">{{ houseDetail.layoutText || houseDetail.layout }}</span>
            </div>
            <div class="feature-item">
              <span class="label">押金类型:</span>
              <span class="value">{{ houseDetail.depositTypeText }}</span>
            </div>
            <div class="feature-item">
              <span class="label">支付方式:</span>
              <span class="value">{{ houseDetail.paymentTypeText }}</span>
            </div>
            <div class="feature-item">
              <span class="label">出租方式:</span>
              <span class="value">{{ houseDetail.houseRentType === 1 ? '房东直售' : houseDetail.houseRentType === 2 ? '中介代理' : '未知类型' }}</span>
            </div>
          </div>

          <div class="house-tags">
            <el-tag
                v-for="tag in houseDetail.tags"
                :key="tag"
                size="small"
                :type="getTagType(tag)"
            >
              {{ tag }}
            </el-tag>
          </div>

          <div class="house-description">
            <h3>房源描述</h3>
            <p>{{ houseDetail.description }}</p>
          </div>

          <div class="house-facilities">
            <h3>配套设施</h3>
            <div class="facilities-list">
              <div
                  class="facility-item"
                  v-for="facility in houseDetail.facilities"
                  :key="facility"
                  :class="{ available: houseDetail.availableFacilities.includes(facility) }"
              >
                <el-icon>
                  <Check v-if="houseDetail.availableFacilities.includes(facility)" />
                  <Close v-else />
                </el-icon>
                <span>{{ facility }}</span>
              </div>
            </div>
          </div>

          <div class="action-buttons">
            <!-- 租客功能 -->
            <template v-if="userType === 'tenant'">
              <el-button type="primary" size="large" @click="contactLandlord">
                {{ houseDetail.houseRentType === 2 ? '联系中介' : '联系房东' }}
              </el-button>
              <el-button size="large" @click="scheduleVisit">
                预约看房
              </el-button>
              <el-button size="large" @click="initiateContract">
                发起签约
              </el-button>
              <el-button
                  :type="houseDetail.favorited ? 'danger' : 'default'"
                  size="large"
                  @click="toggleFavorite"
              >
                <el-icon><Star v-if="houseDetail.favorited" /></el-icon>
                {{ houseDetail.favorited ? '已收藏' : '收藏房源' }}
              </el-button>
            </template>

            <!-- 中介功能 -->
            <template v-if="userType === 'agent'">
              <el-button type="primary" size="large" @click="contactLandlord">
                {{ houseDetail.houseRentType === 2 ? '联系中介' : '联系房东' }}
              </el-button>
              <el-button
                  type="success"
                  size="large"
                  @click="applyForAgency"
              >
                申请代理
              </el-button>
              <el-button
                  :type="houseDetail.favorited ? 'danger' : 'default'"
                  size="large"
                  @click="toggleFavorite"
              >
                <el-icon><Star v-if="houseDetail.favorited" /></el-icon>
                {{ houseDetail.favorited ? '已收藏' : '收藏房源' }}
              </el-button>
            </template>
          </div>
        </div>
      </div>

      <!-- 房东信息区域 -->
      <div v-if="!loading && (houseDetail.realName || houseDetail.landlord)" class="landlord-section">
        <div class="landlord-card">
          <div class="landlord-header">
            <el-avatar
                :size="60"
                :src="houseDetail.landlord?.avatar || '/default-avatar.png'"
            />
            <div class="landlord-info">
              <h3>{{ houseDetail.realName || houseDetail.landlord?.name || (houseDetail.houseRentType === 2 ? '中介' : '房东') }}</h3>
              <p>{{ houseDetail.houseRentType === 2 ? '中介身份已认证' : '房东身份已认证' }}</p>
            </div>
          </div>

          <div class="landlord-contact-info" v-if="houseDetail.phone">
            <div class="contact-item">
              <el-icon><Phone /></el-icon>
              <span>{{ houseDetail.phone }}</span>
            </div>
          </div>

          <div class="landlord-stats">
            <div class="stat-item">
              <div class="stat-value">{{ houseDetail.landlord.listings || 0 }}</div>
              <div class="stat-label">房源数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ houseDetail.landlord.rented || 0 }}</div>
              <div class="stat-label">已出租</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ houseDetail.landlord.rating || '暂无' }}</div>
              <div class="stat-label">评分</div>
            </div>
          </div>

          <div class="landlord-contact">
            <el-button type="primary" @click="contactLandlord">
              <el-icon><ChatLineSquare /></el-icon>
              {{ houseDetail.houseRentType === 2 ? '联系中介' : '联系房东' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 发起签约对话框 -->
    <InitiateContract
        v-model="showContractDialog"
        :house-id="houseDetail.houseId || route.params.id"
        @success="onContractSuccess"
    />

    <!-- 预约看房对话框 -->
    <el-dialog
        v-model="showAppointmentDialog"
        title="预约看房"
        width="500px"
        :before-close="handleAppointmentClose"
    >
      <el-form
          ref="appointmentFormRef"
          :model="appointmentForm"
          :rules="appointmentRules"
          label-width="100px"
      >
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker
              v-model="appointmentForm.appointmentTime"
              type="datetime"
              placeholder="选择预约时间"
              style="width: 100%"
              :disabled-date="disabledDate"
              :disabled-time="disabledTime"
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="contactPhone">
          <el-input
              v-model="appointmentForm.contactPhone"
              placeholder="请输入联系电话"
          />
        </el-form-item>

        <el-form-item label="备注说明">
          <el-input
              v-model="appointmentForm.remarks"
              type="textarea"
              :rows="3"
              placeholder="其他需要说明的情况"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAppointmentDialog = false" :disabled="submittingAppointment">取消</el-button>
          <el-button
            type="primary"
            @click="submitAppointment"
            :loading="submittingAppointment"
            :disabled="submittingAppointment"
          >
            {{ submittingAppointment ? '提交中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </UserLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import UserLayout from '@/components/layout/UserLayout.vue'
import InitiateContract from '@/components/contract/InitiateContract.vue'
import { createChatSession } from '@/utils/apiService'
import { getUserInfo } from '@/utils/auth'
import {
  House,
  Location,
  OfficeBuilding,
  Sunny,
  Check,
  Close,
  Star,
  ChatLineSquare,
  ArrowLeft,
  Phone
} from '@element-plus/icons-vue'
import api from "@/utils/api.js";

const route = useRoute()
const router = useRouter()

// 导航状态
const activeIndex = ref('2') // 房源搜索
const activeMenu = ref('search')

// 临时信息值，用于API请求头
const TEMP_INFO_VALUE = '9fbf0bf9-350d-4fad-8799-acfbfa3dd579'

// 创建带有默认请求头的 axios 实例
const apiClient = axios.create({
  headers: {
    'info': TEMP_INFO_VALUE
  }
})

// 当前选中的图片索引
const activeImageIndex = ref(0)
const showContractDialog = ref(false)
const showAppointmentDialog = ref(false)
const appointmentFormRef = ref()
const userType = ref('tenant') // tenant, agent, landlord
const loading = ref(false)
const submittingAppointment = ref(false) // 预约提交状态

// 预约表单
const appointmentForm = ref({
  appointmentTime: '',
  contactPhone: '',
  remarks: ''
})

// 提交预约时的加载状态
// const submittingAppointment = ref(false)

// 预约表单验证规则
const appointmentRules = {
  appointmentTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 房源详情数据 - 根据API返回的JSON结构定义
const houseDetail = ref({
  // API原始数据字段
  houseId: null,
  landlord: {
    userId: null,
    landlordId: null,
    houses: null,
    isDeleted: null
  },
  houseSummary: '',
  agent: {
    userId: null,
    agentId: null,
    houses: null,
    agentVerifyId: null,
    licenseNo: null,
    isDeleted: null
  },
  complementaryFacilities: {
    complementaryFacilityId: null,
    houseId: null,
    hasFridge: false,
    hasBed: false,
    hasWasher: false,
    hasWaterHeater: false,
    hasWifi: false,
    hasSofa: false,
    hasKitchen: false,
    hasRangeHood: false,
    hasGasStove: false,
    hasTV: false,
    hasAirConditioner: false,
    hasCloset: false,
    hasSmartDoorLock: false,
    hasBalcony: false,
    hasCentralHeating: false,
    hasCupBoard: false,
    hasDiningTable: false
  },
  propertyVerification: {
    propertyVerifyId: null,
    userId: null,
    propertyPicPath: null,
    propertyNo: null,
    propertyAddr: null,
    verifyStatus: null,
    isDeleted: null
  },
  houseLocation: '',
  layout: 0,
  area: 0,
  depositType: 0,
  floor: 0,
  orientation: '',
  status: 0,
  rent: 0,
  paymentType: 0,
  rentType: 0,
  subwayInfo: '',
  createTime: '',
  isDeleted: false,
  longitude: 0,
  latitude: 0,
  phone: '',

  // 用于页面显示的计算字段
  title: '',
  price: 0,
  address: '',
  layoutText: '',
  floorText: '',
  rentTypeText: '',
  paymentTypeText: '',
  depositTypeText: '',
  image: '',
  images: [],
  tags: [],
  facilities: [
    '冰箱', '床', '洗衣机', '热水器', 'WIFI', '沙发',
    '厨房', '油烟机', '燃气灶', '电视', '空调', '衣柜',
    '智能门锁', '阳台', '暖气', '橱柜', '餐桌'
  ],
  availableFacilities: [],
  favorited: false,
  description: ''
})

// 获取房源详情数据
const fetchHouseDetail = async (houseId) => {
  loading.value = true
  try {
    console.log(`正在获取房源详情，ID: ${houseId}`)

    // 验证参数
    if (!houseId) {
      throw new Error('房源ID不能为空')
    }

    // 修改为正确的API路径
    const response = await api.get(`/house/${houseId}`)
    console.log('API完整响应:', response)

    // 由于api.js拦截器返回完整的response对象，业务状态码在response.data.code中
    // 检查响应状态
    if (response.data.code !== 200 && response.data.code !== '200') {
      throw new Error(response.data.message || '获取房源详情失败')
    }

    // 正确提取数据 - 直接从response.data.body获取房源数据
    const data = response.data?.body || response.data
    if (!data) {
      throw new Error('房源数据不存在')
    }

    console.log('API返回数据:', data)

    // 处理显示用的数据（先处理再赋值）
    processHouseData(data)

    // 只设置原始数据字段，避免覆盖已处理的数据
    houseDetail.value.houseId = data.houseId
    houseDetail.value.landlord = data.landlord || {}
    houseDetail.value.agent = data.agent || {}
    houseDetail.value.complementaryFacilities = data.complementaryFacilities || {}
    houseDetail.value.propertyVerification = data.propertyVerification || {}
    houseDetail.value.houseLocation = data.houseLocation || ''
    houseDetail.value.layout = data.layout || 0
    houseDetail.value.area = data.area || 0
    houseDetail.value.depositType = data.depositType || 0
    houseDetail.value.floor = data.floor || 0
    houseDetail.value.orientation = data.orientation || ''
    houseDetail.value.status = data.status || 0
    houseDetail.value.rent = data.rent || 0
    houseDetail.value.paymentType = data.paymentType || 0
    houseDetail.value.rentType = data.rentType || 0
    houseDetail.value.houseRentType = data.houseRentType || data.rentType || 0
    houseDetail.value.subwayInfo = data.subwayInfo || ''
    houseDetail.value.createTime = data.createTime || ''
    houseDetail.value.isDeleted = data.isDeleted || false
    houseDetail.value.longitude = data.longitude || 0
    houseDetail.value.latitude = data.latitude || 0
    houseDetail.value.phone = data.phone || ''
    houseDetail.value.realName = data.realName || ''

    ElMessage.success('房源详情加载成功')
  } catch (error) {
    console.error('获取房源详情失败:', error)

    // 根据错误类型显示不同的错误信息
    let errorMessage = '获取房源详情失败，请稍后重试'

    if (error.response) {
      // HTTP错误响应
      const status = error.response.status
      if (status === 404) {
        errorMessage = '房源不存在或已被删除'
      } else if (status === 403) {
        errorMessage = '没有权限访问此房源'
      } else if (status === 500) {
        errorMessage = '服务器内部错误，请稍后重试'
      } else if (status >= 400 && status < 500) {
        errorMessage = '请求参数错误'
      }
    } else if (error.message) {
      // 自定义错误信息
      errorMessage = error.message
    }

    // 如果是网络错误，尝试使用模拟数据
    if (error.code === 'ERR_NETWORK' || errorMessage.includes('Network Error') || errorMessage.includes('无法连接')) {
      console.log('检测到网络错误，使用模拟数据')
      useMockHouseData(houseId)
      return
    }

    ElMessage.error(errorMessage)

    // 如果获取失败，延迟返回上一页
    setTimeout(() => {
      router.go(-1)
    }, 2000)

    // 重新抛出错误，让调用者知道失败了
    throw error
  } finally {
    loading.value = false
  }
}

// 使用模拟房源数据
const useMockHouseData = (houseId) => {
  console.log('使用模拟房源数据，ID:', houseId)

  const mockData = {
    houseId: houseId,
    title: '精装修两居室，交通便利，拎包入住',
    price: 4500,
    area: 85,
    address: '北京市朝阳区三里屯街道',
    description: '房屋位于繁华的三里屯地区，周边配套设施齐全，交通便利。房屋精装修，家具家电齐全，可拎包入住。小区环境优美，物业管理完善，24小时安保。周边有多个商场、餐厅、健身房等生活配套设施。',
    images: [
      'https://img.ljcdn.com/beike/ajk/92dc8e93-8f5e-4c4b-9c5e-8f5e4c4b9c5e.jpg',
      'https://img.ljcdn.com/beike/ajk/92dc8e93-8f5e-4c4b-9c5e-8f5e4c4b9c5f.jpg',
      'https://img.ljcdn.com/beike/ajk/92dc8e93-8f5e-4c4b-9c5e-8f5e4c4b9c60.jpg'
    ],
    layout: 2,
    floor: 15,
    orientation: '南北',
    rentType: 1,
    paymentType: 1,
    depositType: 1,
    longitude: 116.447764,
    latitude: 39.937576,
    landlord: {
      name: '张先生',
      phone: '138****8888',
      avatar: ''
    },
    agent: null,
    complementaryFacilities: {
      hasWifi: true,
      hasAirConditioner: true,
      hasWashingMachine: true,
      hasRefrigerator: true,
      hasTV: true,
      hasWaterHeater: true
    },
    propertyVerification: {
      isVerified: true,
      verificationTime: '2024-01-15'
    },
    subwayInfo: '距离地铁10号线团结湖站500米',
    createTime: '2024-01-15 10:30:00',
    status: 1
  }

  processHouseData(mockData)

  // 设置房源详情数据
  Object.assign(houseDetail.value, mockData)

  ElMessage.warning('后端服务不可用，已加载模拟数据用于测试')
}

// 数据验证辅助函数
const isValidData = (data) => {
  return data && typeof data === 'object'
}

// 处理房源数据，转换为显示格式
const processHouseData = (data) => {
  if (!isValidData(data)) {
    console.warn('房源数据无效:', data)
    return
  }

  // 设置标题
  houseDetail.value.title = data.houseTitle || '房源详情'

  // 设置价格
  houseDetail.value.price = Number(data.rent) || 0

  // 设置地址
  houseDetail.value.address = data.houseLocation || ''

  // 处理房源照片
  const images = []
  if (data.houseMedia) {
    // 遍历 picPath1 到 picPath10，收集有效的图片URL
    for (let i = 1; i <= 10; i++) {
      const picPath = data.houseMedia[`picPath${i}`]
      if (picPath && picPath.trim() !== '') {
        images.push(picPath)
      }
    }
  }

  // 如果没有图片，使用默认图片
  if (images.length === 0) {
    images.push('https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1769&q=80')
  }

  houseDetail.value.images = images
  houseDetail.value.image = images[0] // 设置主图片为第一张

  // 重置图片索引
  activeImageIndex.value = 0

  // 设置户型文本
  const layoutMap = {
    1: '一居室',
    2: '两居室',
    3: '三居室',
    4: '四居室',
    5: '五居室及以上'
  }
  houseDetail.value.layoutText = layoutMap[data.layout] || '未知户型'

  // 设置楼层文本
  houseDetail.value.floorText = `第${data.floor}层`

  // 设置租赁类型文本
  const rentTypeMap = {
    1: '房东直售',
    2: '中介代理'
  }

  // 优先使用 houseRentType，如果不存在则使用 rentType
  const rentTypeValue = data.houseRentType !== undefined ? data.houseRentType : data.rentType
  houseDetail.value.rentTypeText = rentTypeMap[rentTypeValue] || '未知类型'
  houseDetail.value.rentType = rentTypeMap[rentTypeValue] || '未知类型'

  // 设置支付类型文本
  const paymentTypeMap = {
    1: '月付',
    2: '季付',
    3: '半年付',
    4: '年付'
  }
  houseDetail.value.paymentTypeText = paymentTypeMap[data.paymentType] || '面议'

  // 设置押金类型文本
  const depositTypeMap = {
    1: '押一付一',
    2: '押一付三',
    3: '押二付一',
    4: '押三付一'
  }
  houseDetail.value.depositTypeText = depositTypeMap[data.depositType] || '面议'

  // 处理配套设施
  if (data.complementaryFacilities) {
    const facilities = data.complementaryFacilities
    const availableFacilities = []

    if (facilities.hasFridge) availableFacilities.push('冰箱')
    if (facilities.hasBed) availableFacilities.push('床')
    if (facilities.hasWasher) availableFacilities.push('洗衣机')
    if (facilities.hasWaterHeater) availableFacilities.push('热水器')
    if (facilities.hasWifi) availableFacilities.push('WIFI')
    if (facilities.hasSofa) availableFacilities.push('沙发')
    if (facilities.hasKitchen) availableFacilities.push('厨房')
    if (facilities.hasRangeHood) availableFacilities.push('油烟机')
    if (facilities.hasGasStove) availableFacilities.push('燃气灶')
    if (facilities.hasTV) availableFacilities.push('电视')
    if (facilities.hasAirConditioner) availableFacilities.push('空调')
    if (facilities.hasCloset) availableFacilities.push('衣柜')
    if (facilities.hasSmartDoorLock) availableFacilities.push('智能门锁')
    if (facilities.hasBalcony) availableFacilities.push('阳台')
    if (facilities.hasCentralHeating) availableFacilities.push('暖气')
    if (facilities.hasCupBoard) availableFacilities.push('橱柜')
    if (facilities.hasDiningTable) availableFacilities.push('餐桌')

    houseDetail.value.availableFacilities = availableFacilities
  } else {
    houseDetail.value.availableFacilities = []
  }

  // 生成标签
  const tags = []
  if (data.subwayInfo) tags.push('近地铁')
  if (data.status === 1) tags.push('可租')
  if (data.complementaryFacilities?.hasWifi) tags.push('有WIFI')
  if (data.complementaryFacilities?.hasAirConditioner) tags.push('有空调')
  if (data.complementaryFacilities?.hasKitchen) tags.push('有厨房')
  if (data.complementaryFacilities?.hasWasher) tags.push('有洗衣机')
  if (data.complementaryFacilities?.hasSmartDoorLock) tags.push('智能门锁')

  houseDetail.value.tags = tags

  // 设置描述
  let description = data.houseSummary || '暂无描述'
  if (data.houseLocation) {
    description += `\n\n📍 位置：${data.houseLocation}`
  }
  if (data.subwayInfo) {
    description += `\n🚇 交通：${data.subwayInfo}`
  }
  if (data.phone) {
    description += `\n📞 联系电话：${data.phone}`
  }
  if (data.createTime) {
    const createDate = new Date(data.createTime).toLocaleDateString()
    description += `\n📅 发布时间：${createDate}`
  }

  houseDetail.value.description = description
}

// 获取标签类型
const getTagType = (tag) => {
  const tagTypes = {
    '近地铁': 'success',
    '精装修': 'warning',
    '拎包入住': 'info',
    '新上架': 'danger',
    '学区房': 'primary',
    '地铁房': 'success',
    '别墅': 'primary',
    '带花园': 'success',
    '独栋': 'warning',
    '可租': 'success',
    '有WIFI': 'info',
    '有空调': 'warning',
    '有厨房': 'primary',
    '有洗衣机': 'info',
    '智能门锁': 'danger'
  }
  return tagTypes[tag] || 'info'
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 联系房东/中介
const contactLandlord = () => {
  if (houseDetail.value.phone) {
    const isAgent = houseDetail.value.houseRentType === 2
    const contactType = isAgent ? '中介' : '房东'
    // 显示联系方式
    ElMessageBox.alert(
        `${contactType}联系电话：${houseDetail.value.phone}`,
        `联系${contactType}`,
        {
          confirmButtonText: '确定',
          type: 'info'
        }
    )
  } else {
    ElMessage.warning('暂无联系方式')
  }
}

// 预约看房
const scheduleVisit = async () => {
  // 先检查是否已有未完成的预约
  const hasActiveAppointment = await checkActiveAppointment()
  if (hasActiveAppointment) {
    return // 如果有活跃预约，直接返回
  }

  // 获取用户信息，用于初始化联系电话
  const user = localStorage.getItem('user')
  let userPhone = ''
  if (user) {
    try {
      const userData = JSON.parse(user)
      userPhone = userData.phone || userData.mobile || ''
    } catch (e) {
      console.error('解析用户信息失败', e)
    }
  }

  // 初始化表单数据
  appointmentForm.value = {
    appointmentTime: '',
    contactPhone: userPhone, // 优先使用用户自己的电话
    remarks: ''
  }
  showAppointmentDialog.value = true
}

// 检查是否有活跃的预约（未被拒绝且未完成的预约）
const checkActiveAppointment = async () => {
  const user = localStorage.getItem('user')
  if (!user) {
    ElMessage.error('请先登录')
    return true
  }

  try {
    const userData = JSON.parse(user)
    const userId = userData.id || userData.userId
    const currentHouseId = parseInt(houseDetail.value.houseId || route.params.id)

    // 获取用户的预约列表
    const response = await api.get(`/appointment/list/${userId}`)

    if (response && (response.data.code === 200 || response.data.code === '200')) {
      const appointments = response.data.data || []

      // 检查是否有针对当前房源的活跃预约
      const activeAppointments = appointments.filter(appointment => {
        return appointment.houseId === currentHouseId &&
               (appointment.isRefused === null || appointment.isRefused === false)
      })

      if (activeAppointments.length > 0) {
        const latestAppointment = activeAppointments[activeAppointments.length - 1]
        const appointmentTime = new Date(latestAppointment.appointmentTime).toLocaleString('zh-CN')

        if (latestAppointment.isRefused === false) {
          ElMessage.warning(`您已有一个确认的预约（${appointmentTime}），请完成后再预约`)
        } else {
          ElMessage.warning(`您已有一个待确认的预约（${appointmentTime}），请等待确认结果`)
        }
        return true
      }
    }
  } catch (error) {
    console.error('检查预约状态失败:', error)
    // 如果检查失败，允许继续预约，但给出提示
    ElMessage.warning('无法检查预约状态，请确保没有重复预约')
  }

  return false
}

// 禁用过去的日期
const disabledDate = (date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return date.getTime() < today.getTime()
}

// 禁用时间（示例：只允许工作时间）
const disabledTime = (date) => {
  if (!date) return {}

  const isWeekend = date.getDay() === 0 || date.getDay() === 6

  // 周末只允许9:00-18:00
  if (isWeekend) {
    return {
      disabledHours: () => [
        0, 1, 2, 3, 4, 5, 6, 7, 8, 18, 19, 20, 21, 22, 23
      ]
    }
  }

  // 工作日允许9:00-21:00
  return {
    disabledHours: () => [
      0, 1, 2, 3, 4, 5, 6, 7, 8, 21, 22, 23
    ]
  }
}

// 关闭预约对话框前的处理
const handleAppointmentClose = (done) => {
  ElMessageBox.confirm('确认关闭预约看房页面吗？')
      .then(() => {
        done()
      })
      .catch(() => {
        // 取消关闭
      })
}

// 提交预约
const submitAppointment = async () => {
  if (!appointmentFormRef.value) {
    ElMessage.error('表单未初始化')
    return
  }

  if (submittingAppointment.value) {
    ElMessage.warning('正在提交中，请稍候...')
    return
  }

  submittingAppointment.value = true

  try {
    const valid = await appointmentFormRef.value.validate()
    if (!valid) {
      ElMessage.error('请填写完整信息')
      return
    }

    // 获取用户信息 - 尝试多种存储方式
    let userData = null
    const user = localStorage.getItem('user') || localStorage.getItem('userInfo')
    if (!user) {
      ElMessage.error('请先登录')
      return
    }

    try {
      userData = JSON.parse(user)
      console.log('获取到的用户信息:', userData)
    } catch (error) {
      console.error('解析用户信息失败:', error)
      ElMessage.error('用户信息格式错误，请重新登录')
      return
    }

    // 处理时间格式，转换为Java LocalDateTime能识别的ISO格式
    let formattedTime = appointmentForm.value.appointmentTime
    if (formattedTime instanceof Date) {
      // 转换为ISO格式字符串，但去掉时区信息：YYYY-MM-DDTHH:mm:ss
      const year = formattedTime.getFullYear()
      const month = String(formattedTime.getMonth() + 1).padStart(2, '0')
      const day = String(formattedTime.getDate()).padStart(2, '0')
      const hours = String(formattedTime.getHours()).padStart(2, '0')
      const minutes = String(formattedTime.getMinutes()).padStart(2, '0')
      const seconds = String(formattedTime.getSeconds()).padStart(2, '0')
      formattedTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`
    }

    // 准备预约数据 - 根据数据库字段名匹配
    const appointmentData = {
      // API文档要求的基本字段
      houseId: parseInt(houseDetail.value.houseId || route.params.id),
      appointmentTime: formattedTime, // 使用格式化后的时间
      tenantPhone: appointmentForm.value.contactPhone, // 修正字段名：contactPhone -> tenantPhone

      // 数据库需要的额外字段
      tenantId: userData.id || userData.userId, // 当前用户ID
      landlordId: houseDetail.value.landlord?.landlordId || null, // 房东ID
      agentId: houseDetail.value.agent?.agentId || null, // 中介ID（如果有）
      remarkMessage: appointmentForm.value.remarks || null // 修正字段名：remarkmessage -> remarkMessage
    }

    console.log('房源详情信息:', {
      houseId: houseDetail.value.houseId,
      landlord: houseDetail.value.landlord,
      agent: houseDetail.value.agent
    })
    console.log('提交预约数据:', appointmentData)

    // 验证必要字段
    if (!appointmentData.tenantId) {
      ElMessage.error('无法获取用户ID，请重新登录')
      return
    }
    if (!appointmentData.houseId) {
      ElMessage.error('房源ID无效')
      return
    }

    // 调用API提交预约
    const response = await api.post('/appointment', appointmentData)

    console.log('预约提交响应:', response)
    console.log('HTTP状态码:', response.status)
    console.log('业务状态码:', response.data?.code)
    console.log('响应数据类型:', typeof response)

    // 根据实际的响应结构判断成功
    // 从控制台看，响应直接就是 {code: "200", data: "成功预约", message: null}
    if (response && (response.data.code === 200 || response.data.code === '200')) {
      // 成功情况：response.data.code是200
      ElMessage.success(response.data.data || '预约已提交，请等待房东确认')
      showAppointmentDialog.value = false

      // 可以跳转到预约结果页面
      // router.push('/tenant/appointment')
    } else {
      // 失败情况
      const errorMessage = response.data?.message || '预约提交失败'
      ElMessage.error(errorMessage)
      console.error('预约提交失败，错误码:', response.data?.code, '错误信息:', errorMessage)
    }
  } catch (error) {
    console.error('提交预约失败:', error)
    if (error.response) {
      ElMessage.error(error.response.data?.message || '预约提交失败')
    } else {
      ElMessage.error('网络错误，请重试')
    }
  } finally {
    submittingAppointment.value = false
  }
}

// 发起签约
const initiateContract = () => {
  showContractDialog.value = true
}

// 合约成功提交
const onContractSuccess = () => {
  ElMessage.success('签约申请已提交')
}

// 申请代理
const applyForAgency = () => {
  ElMessageBox.confirm(
      '确定要申请代理此房源吗？',
      '申请代理',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 模拟申请代理的API调用
    setTimeout(() => {
      ElMessage.success('申请已提交，请等待审核')
      // 申请成功后返回可代理房源列表
      router.push('/agent/houses')
    }, 1000)
  }).catch(() => {
    // 用户取消操作
  })
}

// 切换收藏状态
const toggleFavorite = () => {
  houseDetail.value.favorited = !houseDetail.value.favorited
  ElMessage.success(houseDetail.value.favorited ? '已收藏' : '已取消收藏')
}

// 页面加载时的处理
onMounted(async () => {
  // 获取房源ID并请求详细信息
  const houseId = route.params.id
  console.log('房源ID:', houseId)

  // 验证房源ID的有效性
  if (!houseId) {
    ElMessage.error('房源ID不存在')
    router.go(-1)
    return
  }

  // 验证房源ID是否为有效的数字或字符串
  if (typeof houseId !== 'string' && typeof houseId !== 'number') {
    ElMessage.error('房源ID格式无效')
    router.go(-1)
    return
  }

  // 如果是字符串，检查是否为空或只包含空白字符
  if (typeof houseId === 'string' && houseId.trim() === '') {
    ElMessage.error('房源ID不能为空')
    router.go(-1)
    return
  }

  try {
    await fetchHouseDetail(houseId)
  } catch (error) {
    console.error('加载房源详情时发生错误:', error)
    // fetchHouseDetail 内部已经处理了错误，这里不需要额外处理
  }

  // 模拟从localStorage获取用户信息
  const user = localStorage.getItem('user')
  if (user) {
    try {
      const userData = JSON.parse(user)

      // 角色映射：数字到字符串的转换
      const roleMapping = {
        1: 'tenant',    // 1 = 租客
        2: 'landlord',  // 2 = 房东
        4: 'agent'      // 4 = 中介
      }

      // 根据用户角色设置userType
      let roleValue = userData.role || userData.userType

      if (roleValue !== undefined) {
        // 如果是数字，转换为对应的字符串
        if (typeof roleValue === 'number') {
          userType.value = roleMapping[roleValue] || 'tenant'
        } else {
          // 如果已经是字符串，直接使用
          userType.value = roleValue
        }
      } else {
        // 如果没有角色信息，默认设置为租客
        userType.value = 'tenant'
      }
    } catch (e) {
      console.error('解析用户信息失败', e)
      // 如果用户信息解析失败，使用默认的租客角色
      userType.value = 'tenant'
    }
  } else {
    // 如果没有用户信息，默认设置为租客（允许游客查看）
    userType.value = 'tenant'
  }
})
</script>

<style scoped>
.house-detail-container {
  display: flex;
  min-height: 100vh;
  overflow: hidden;
  position: relative;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

/* 精美的动态背景 */
.dynamic-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, #1a2980, #26d0ce);
  overflow: hidden;
}

/* 建筑物 */
.building {
  position: absolute;
  bottom: 0;
  background: rgba(30, 30, 50, 0.8);
  border-radius: 5px 5px 0 0;
  box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
}

/* 页面内容样式 */
.header-section {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.detail-content {
  display: flex;
  gap: 30px;
  background: #fff;
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.image-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.main-image {
  height: 400px;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.main-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail-images {
  display: flex;
  gap: 15px;
  overflow-x: auto;
  padding: 5px;
}

.thumbnail {
  width: 100px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid transparent;
  flex-shrink: 0;
  transition: all 0.3s ease;
}

.thumbnail:hover,
.thumbnail.active {
  border-color: #409EFF;
  transform: translateY(-3px);
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.house-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.house-title {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
}

.house-price {
  font-size: 32px;
  font-weight: 700;
  color: #409EFF;
}

.house-price span {
  font-size: 16px;
  font-weight: normal;
}

.house-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 15px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #7f8c8d;
}

.house-features {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.feature-item {
  display: flex;
  gap: 10px;
}

.feature-item .label {
  font-weight: 600;
  color: #2c3e50;
}

.feature-item .value {
  color: #7f8c8d;
}

.house-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 15px 0;
}

.house-description h3,
.house-facilities h3 {
  margin: 0 0 15px;
  font-size: 20px;
  color: #2c3e50;
}

.house-description p {
  margin: 0;
  line-height: 1.6;
  color: #7f8c8d;
}

.facilities-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.facility-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #7f8c8d;
}

.facility-item.available {
  color: #67C23A;
}

.facility-item .el-icon {
  font-size: 16px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  padding-top: 20px;
  margin-top: auto;
}

.action-buttons .el-button {
  flex: 1;
}

.landlord-section {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
}

.landlord-card {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.landlord-header {
  display: flex;
  align-items: center;
  gap: 20px;
}

.landlord-header h3 {
  margin: 0 0 5px;
  font-size: 20px;
  color: #2c3e50;
}

.landlord-header p {
  margin: 0;
  font-size: 14px;
  color: #7f8c8d;
  display: flex;
  align-items: center;
  gap: 5px;
}

.certified-icon {
  color: #67C23A;
}

.landlord-contact-info {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 15px;
}

.contact-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #7f8c8d;
}

.contact-item:last-child {
  margin-bottom: 0;
}

.landlord-stats {
  display: flex;
  justify-content: space-around;
  background: #f8f9fa;
  border-radius: 10px;
  padding: 20px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #409EFF;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

.landlord-contact .el-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
}

/* 预约对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 992px) {
  .detail-content {
    flex-direction: column;
  }

  .house-header {
    flex-direction: column;
    gap: 15px;
  }

  .house-features,
  .facilities-list {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
  }

  .landlord-stats {
    flex-direction: column;
    gap: 15px;
  }
}
</style>